/*
 * The MIT License (MIT)
 *
 * Copyright (c) 2014-2016 abel533@gmail.com
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 */

package tk.mybatis.springboot.service;

import jxl.Workbook;
import jxl.format.Colour;
import jxl.format.UnderlineStyle;
import jxl.write.*;
import jxl.write.biff.RowsExceededException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import tk.mybatis.springboot.mapper.AccountMapper;
import tk.mybatis.springboot.mapper.LoginMapper;
import tk.mybatis.springboot.mapper.PersoninfoMapper;
import tk.mybatis.springboot.model.Account;
import tk.mybatis.springboot.model.Person;
import tk.mybatis.springboot.model.PersonVO;
import tk.mybatis.springboot.util.UUIDGenerator;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import java.util.List;
import java.util.UUID;

/**
 * @author liuzh
 * @since 2015-12-19 11:09
 */
@Service
public class PersonService {
    @Autowired
    private AccountMapper accountMapper;
    @Autowired
    private PersoninfoMapper personinfoMapper;

    public List<PersonVO> getAllPerson(PersonVO personVO){
        int rows= personVO.getRows();
        int page= personVO.getPage()-1;
        List<PersonVO> persons=personinfoMapper.getAllPerson(rows,page);
        return persons;
    }

    public int countAllPerson(PersonVO personVO) {
        return personinfoMapper.countAllPerson(personVO.getStatus());
    }

    public int changeStatus(String id, String status) {
        Account account=new Account();
        account.setId(id);
        account.setStatus(status);
        return accountMapper.updateByPrimaryKeySelective(account);
    }

    public int deleteInfo(String id) {
        accountMapper.deleteByPrimaryKey(id);
        Person person=new Person();
        person.setAccountid(id);
        return personinfoMapper.delete(person);
    }

    public List<PersonVO> getPerson(PersonVO personVO) {
        int rows= personVO.getRows();
        int page= personVO.getPage()-1;
        List<PersonVO> persons=personinfoMapper.getPerson(rows,page,personVO.getStatus());

        return persons;
    }

    @Transactional
    public int submitInfo(PersonVO personVO) throws Exception {
        Account account=new Account();
        account.setUsername(personVO.getUsername());
        if(accountMapper.select(account).size()>0){
            throw new Exception("该用户名已注册");
        }

        String id=UUIDGenerator.getUUID();
        account.setId(id);
        account.setStatus("启用");
        account.setBalance(personVO.getBalance());
        account.setPassword(personVO.getPassword());
        account.setRole(personVO.getRole());


        int i=accountMapper.insert(account);
        int pi=0;
        if(i==1){
            Person person=new Person();
            person.setId(UUIDGenerator.getUUID());
            person.setAccountid(id);
            person.setRealname(personVO.getRealname());
            person.setSex(personVO.getSex());
            person.setAge(personVO.getAge());
            person.setAddress(personVO.getAddress());
            person.setTelephone(personVO.getTelephone());
            person.setCardid(personVO.getCardid());
             pi=personinfoMapper.insert(person);
            if (pi!=1){
                accountMapper.delete(account);
            }
        }
        return pi;
    }

    /**
     * 生成excel文件 在D:\
     * 1生成登陆日志
     * 2生成操作日志
     * @param
     * @return
     */
    public File getExcel(List<PersonVO> list){
        /*List<ShowLog> list = null;
        if (logType == 1) {
            list = loginLogService.getAllShowLoginLog();
        }else if(logType == 2){
            list = operationLogService.getAllShowLog();
        }*/
       // List<Customer> list=customerService.findAll();

        File file  = new File("d:\\fileupload\\所有账户信息"+ System.currentTimeMillis() +".xls");
        WritableWorkbook workbook = null;
        try {
            workbook = Workbook.createWorkbook(file);
            WritableSheet sheet = workbook.createSheet("sheet1", 0);
            WritableCellFormat wcf = new WritableCellFormat();
            wcf.setBackground(Colour.YELLOW);
            sheet.addCell(new Label(0, 0, "账户"   , wcf));
            sheet.addCell(new Label(1, 0, "用户名" ,wcf));
            sheet.addCell(new Label(2, 0, "账户余额", wcf));
            sheet.addCell(new Label(3, 0, "姓名"  , wcf));
            sheet.addCell(new Label(4, 0, "地址" , wcf));
            sheet.addCell(new Label(5, 0, "身份证" , wcf));
            sheet.addCell(new Label(6, 0, "电话号码", wcf));
            sheet.addCell(new Label(7, 0, "状态", wcf));
            sheet.setColumnView(0, 40);
            sheet.setColumnView(1, 20);
            sheet.setColumnView(2, 20);
            sheet.setColumnView(3, 20);
            sheet.setColumnView(4, 20);
            sheet.setColumnView(5, 40);
            sheet.setColumnView(6, 30);
            sheet.setColumnView(7, 20);
            for (int row = 0; row < list.size(); row++) {
                sheet.addCell(new Label(0, row+1, list.get(row).getId()));
                sheet.addCell(new Label(1, row+1, list.get(row).getUsername()));
                sheet.addCell(new Label(2, row+1, list.get(row).getBalance()+""));
                sheet.addCell(new Label(3, row+1, list.get(row).getRealname()));
                sheet.addCell(new Label(4, row+1, list.get(row).getAddress()));
                sheet.addCell(new Label(5, row+1, list.get(row).getCardid()));
                sheet.addCell(new Label(6, row+1, list.get(row).getTelephone()));
                sheet.addCell(new Label(7, row+1, list.get(row).getStatus()));

            }

        } catch (IOException e) {
            e.printStackTrace();
        } catch (RowsExceededException e) {
            e.printStackTrace();
        } catch (WriteException e) {
            e.printStackTrace();
        }finally {
            if (workbook != null) {
                try {
                    workbook.write();
                    workbook.close();
                } catch (IOException e) {
                    e.printStackTrace();
                } catch (WriteException e) {
                    e.printStackTrace();
                }
            }
        }

        return file;

    }

    public List<PersonVO> getPersonList() {
        List<PersonVO> personList=personinfoMapper.getPersonList();
        return personList;
    }

    public int importExcel(List<List<String>> list) throws Exception {
        int k=0;
        if (list != null) {
            for (int i = 1; i < list.size(); i++) {
                List<String> cellList = list.get(i);
                PersonVO personVo=new PersonVO();
                personVo.setUsername(cellList.get(0));
                personVo.setBalance(Double.parseDouble(cellList.get(1)));
                personVo.setRealname(cellList.get(2));
                personVo.setAddress(cellList.get(3));
                personVo.setCardid(cellList.get(4));
                personVo.setTelephone(cellList.get(5));
                personVo.setRole(cellList.get(6));
                personVo.setAge(Integer.parseInt(cellList.get(7).substring(0,cellList.get(7).lastIndexOf("."))));//处理excel传值为18.0的情况
                personVo.setSex(cellList.get(8));
                personVo.setPassword("123456");
                k+= submitInfo(personVo);
            }

        }
        return k;
    }
}
